package com.sinai.mshab.client.search;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * This class stores the structure of the database.
 * 
 * @author serge
 * 
 */
public class DatabaseStructure {

	private ArrayList<Field> tables = new ArrayList<Field>();
	private HashMap<String, ArrayList<Field>> tableToFields = new HashMap<String, ArrayList<Field>>();

	public DatabaseStructure() {

	}

	/**
	 * Returns the table names.
	 * 
	 * @param table
	 *            the table name for which to retrieve
	 * @return
	 */
	public ArrayList<String> getTableNames() {
		return new ArrayList<String>(tableToFields.keySet());
	}

	/**
	 * Returns the fields of a give table
	 * 
	 * @param table
	 *            the table for which to return the fields
	 * @return Returns the fields of a give table
	 */
	public ArrayList<Field> getFields(String table) {
		return tableToFields.get(table);
	}

	/**
	 * Returns the type given a table name and a column name
	 * 
	 * @param table
	 *            the table the column belongs to
	 * @param field_name
	 *            the name of the column
	 * @return
	 */
	public String getType(String table, String field_name) {
		ArrayList<Field> fields = getFields(table);
		for (int i = 0; i < fields.size(); i++) {
			Field current = fields.get(i);
			if (current.getName().equals(field_name)) {
				return current.getType();
			}
		}
		return "";
	}

	/**
	 * Add a table to the structure
	 * 
	 * @param table
	 *            the table to add
	 */
	public void addTable(String table) {
		if (!tableToFields.containsKey(table)) {
			tableToFields.put(table, new ArrayList<Field>());
		}
	}

	/**
	 * Add a field to the database structure
	 * 
	 * @param table
	 *            the table to which the field belongs
	 * @param field
	 *            the new field to be added.
	 */
	public void addField(String table, Field field) {

		// check if the table exists
		if (!tableToFields.containsKey(table)) {
			addTable(table);
		}

		ArrayList<Field> fields = tableToFields.get(table);
		fields.add(field);
	}
}
